import {Action, ActionPanel, Detail, getPreferenceValues, LaunchProps, List, useNavigation} from "@raycast/api";
import * as fs from "fs";
import * as kdbxweb from "kdbxweb";
import {AutoType, KeyCode, Modifier} from "keyboard-auto-type";
import _ from "lodash"
import {useEffect, useState} from "react";

const SearchPassword = (props: LaunchProps<{ arguments: { title?: string } }>) => {
    const nav = useNavigation()
    const [kdbx, setKdbx] = useState<kdbxweb.Kdbx>()
    const [message, setMessage] = useState<string>()
    const {kdbx_file, kdbx_password} = getPreferenceValues()
    const [entries, setEntries] = useState<kdbxweb.KdbxEntry[]>()
    const [entriesItems, setEntriesItems] = useState<kdbxweb.KdbxEntry[]>()

    /**
     * 加载Kdbx文件
     */
    const loadKdbx = async () => {
        try {
            const credentials = new kdbxweb.Credentials(kdbxweb.ProtectedValue.fromString(kdbx_password));
            const data = await fs.readFileSync(kdbx_file);
            return await kdbxweb.Kdbx.load(new Uint8Array(data).buffer, credentials)
        } catch (e) {
            setMessage("# kdbx load error")
        }
    }

    /**
     * 初始化
     */
    useEffect(() => {
        loadKdbx().then(kdbx_ => {
            if (kdbx_) {
                if (props.arguments.title) {
                    setEntries(Array.from(kdbx_.getDefaultGroup().allEntries()))
                    setKdbx(kdbx_)
                }
            }
        })

    }, [])

    /**
     * 监听kdbx初始化进行首次查询
     */
    useEffect(() => {
        if (kdbx) {
            searchEntry(props.arguments.title)
        }
    }, [kdbx])


    /**
     * 查询条目
     * @param text
     */
    const searchEntry = (text?: string) => {
        setEntriesItems(entries?.filter(item => item.fields.get("Title")?.includes(text ?? '')))
    }

    /**
     * 渲染查询结果
     */
    const renderEntriesItems = () => entriesItems?.map((item, index) => {
            // console.log("item",item)
            const passwordProtected = item.fields.get("Password") as kdbxweb.ProtectedValue
            const username = item.fields.get("UserName")
            const passwordText = new kdbxweb.ProtectedValue(passwordProtected.value, passwordProtected.salt).getText()
            return <List.Item
                key={index}
                subtitle={`#${index + 1}`}
                title={item.fields.get("Title") as string ?? "未命名"}
                actions={
                    <ActionPanel>
                        <Action title="Select" onAction={() => {

                            // TODO: 实现自动填充
                            const typer = new AutoType();
                            const win = typer.activeWindow({getWindowTitle: true, getBrowserUrl: true});
                            console.log('Going to type in this window', win);
                            typer.text('Hello');
                            typer.keyPress(KeyCode.D1, Modifier.Shift);
                            typer.shortcut(KeyCode.A);
                        }}
                        />
                    </ActionPanel>
                }
            />
        }
    )


    return _.isUndefined(entries) ? <Detail
        markdown={message ?? "# loading ... "}
    /> : <List
        filtering={false}
        navigationTitle="查询结果"
        onSearchTextChange={searchEntry}
        searchBarPlaceholder="Search your favorite beer"
    >
        {renderEntriesItems()}
    </List>
}

export default SearchPassword

